import 'dart:math';

import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:love_newf/app/com/http/Res.dart';
import 'package:love_newf/app/com/http/http_request.dart';
import 'package:love_newf/app/com/manage/location_manage/location_manage.dart';
import 'package:love_newf/app/com/model/room_info_model.dart';
import 'package:love_newf/app/com/model/room_type_model.dart';
import 'package:love_newf/app/com/util/permission_utils.dart';
import 'package:love_newf/app/page/live/live_view.dart';

class OpenLiveSettingLogic extends GetxController {
  var roomNumberTypes = ["三人间", "七人间", "九人间"];
  var roomNumberTypeIndex = 0;
  var selectRoomTypeIndex = 0;
  var firstMsg = [
    "希望看到你更多发言！",
    "你好呀，多和大家聊聊天吧！",
    "欢迎来到我的房间！",
    "今天心情怎么样",
    "欢迎来到直播间，点关注不迷路",
    "人多人少，气势不倒。",
    "在这个美好时刻，我愿意与你们一起分享我的快乐和喜悦"
  ][Random().nextInt(6)];

  List<RoomTypeModel>? debutRoomListResult;
  var roomMap = <int, List<RoomTypeModel>>{0: [], 1: [], 2: []};

  getData() async {
    debutRoomListResult = await HttpRequest().postList<RoomTypeModel>(
        "/api/room/getAllRoomType", null,
        loadingText: "加载中");

    for (RoomTypeModel item in debutRoomListResult ?? []) {
      if (item.roomType == 1 || item.roomType == 2) {
        roomMap[0]!.add(item);
      } else if ([4, 5, 6, 7].contains(item.roomType)) {
        roomMap[1]!.add(item);
      } else if ([8, 9].contains(item.roomType)) {
        roomMap[2]!.add(item);
      }
    }
    update();
  }

  createLive() async {
    RoomTypeModel item;
    try {
      item = roomMap[roomNumberTypeIndex]![selectRoomTypeIndex];
    } catch (_) {
      EasyLoading.showInfo("请选择麦位模式！");
      return;
    }

    if (!await PermissionUtils.checkCameraPermission()) return;
    if (!await PermissionUtils.checkMicrophonePermission()) return;
    RoomInfoModel? info = await HttpRequest().post<RoomInfoModel>(
        "/api/room/createRoom",
        {
          "roomType": item.roomType,
          "name": item.name,
          "firstMsg": firstMsg,
          "province": LocationManage.instance.currLocInfo?.province ?? "",
          "latitude":
              LocationManage.instance.currLocInfo?.latitude.toString() ?? "",
          "longitude":
              LocationManage.instance.currLocInfo?.longitude.toString() ?? "",
        },
        loadingText: "创建中...");
    if (info != null) {
      LivePage.openPage(info.id);
    }
  }
}
